using Codice.Client.Common;
using NL;
using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEngine;
using System.Threading.Tasks;
using System.Text;
using System.Diagnostics;
using Debug = UnityEngine.Debug;


namespace Miya.Hellow.Editor
{
    //  APK IPA 
    public partial class Builder
    {


        public static string PATH_OUTPUT;
        // 输出目录
        public static string PATH_BUILDING_OUT => $"{Application.dataPath}/../_RELEASE";

        // 版本 字符串..来自工程PlayerSetting设置..格式化为  1.02.03
        public static string VERSION_STRING
        {
            get
            {
                var V = new Version(Application.version);
                return V.ToString(1, 2, 2, 0);
            }
        }
        // 版本号----用于标记版本信息的最后一段...
        static int VERSION_CODE => PlayerSettings.Android.bundleVersionCode;

        public static string PATH_HOTASSETS => $"{Application.dataPath}/../HotAssets";





        

        /// <summary>
        /// Jenkins呼叫的 构建入口
        /// </summary>
        [MenuItem("MIYA/Build/BuildByShell--TEST")]
        public static void BuildByShell()
        {
            ///1 读取外部构建参数 
            ApplyShellBuildParam();


            BuildALL();


            //发布
            Publish();
        }

        // 构建参数文件--来自 系统外壳...
        static string FILE_BUILD_PARAM => Path.Combine($"{Application.dataPath}/../", "build.param");

        //包内 版本文件 version.info
        static string FILE_VERSION_INAPPP => Path.Combine(Application.streamingAssetsPath, "version.info");

        static bool BUILD_AAB_PACK = false;

        public static int BUILD_NUM = 0;

        public static string FOLDER = "";

        public static string TAG = "";
        static NLIni info_version;

        static bool BUILD_DEBUGING = false;

        static string PATH_PUBLISH;
        public static void ApplyShellBuildParam()
        {
            Debug.Log($"[JenkinsBuilder.ApplyShellBuildParam]: 开始读取构建参数...{FILE_BUILD_PARAM}");
            if (!File.Exists(FILE_BUILD_PARAM)) return;

            // 读取构建参数............
            var text = File.ReadAllText(FILE_BUILD_PARAM);
            if (string.IsNullOrEmpty(text)) return;

            NLIni info_buildparam = new NLIni(text, '\n');

            if (File.Exists(FILE_VERSION_INAPPP))
            {
                text = File.ReadAllText(FILE_VERSION_INAPPP);
            }
            else
            {
                text = "";
            }

            info_version = new NLIni(text, '\n');
            info_version.Add(info_buildparam, true);

            //////////////版本号..
            PlayerSettings.bundleVersion = info_version["version"];

            //////////////构建编号.整数..
            BUILD_NUM = info_version["buildnum"].AsIntDefault(0);

            //////////////渠道..
            FOLDER = info_version["folder"];

            TAG = info_version["tag"];

            //判断对调试模式的开启
            BUILD_DEBUGING = info_version["debuging"].AsInt > 0;

            EditorUserBuildSettings.development = EditorUserBuildSettings.connectProfiler = BUILD_DEBUGING;

            // 发布目录
            PATH_PUBLISH = info_version["publish"];

            //EditorUserBuildSettings.buildWithDeepProfilingSupport= EditorUserBuildSettings.allowDebugging 

#if UNITY_ANDROID
            PlayerSettings.Android.bundleVersionCode = BUILD_NUM;
			
#elif UNITY_IOS
            PlayerSettings.iOS.buildNumber = BUILD_NUM.ToString();

#elif UNITY_WEBGL
            //  PlayerSettings.WebGL.
#endif


            //AAB 打包?
#if UNITY_ANDROID
            BUILD_AAB_PACK = string.IsNullOrEmpty(info_version["buildAAB"]) ? false : info_version["buildAAB"] == "true";
#else
            BUILD_AAB_PACK = false;
#endif

            Debug.Log($"EditorUserBuildSettings.buildAppBundle={EditorUserBuildSettings.buildAppBundle}, PlayerSettings.Android.useAPKExpansionFiles={PlayerSettings.Android.useAPKExpansionFiles}");

            File.WriteAllText(FILE_VERSION_INAPPP, info_version.ToString('\n'));

            Debug.Log($"[JenkinsBuilder._ApplyShellBuildParam]:Success:.......................... {info_version}");


            ////////////////版本号... >>>> 1.包内的版本清单  2.工程版本信息
            //string version = info_buildparam["version"].AsString;

            //ShellIni _versionIni = new ShellIni(FILE_VERSION_INAPPP);
            //_versionIni.Set("version", version,"APP");

            //PlayerSettings.bundleVersion = version;

            ////////////////构建编号.整数... >>>> 1.包内的  2.工程
            //int buildnum = info_buildparam["buildnum"].AsInt;
            //_versionIni.Set("buildnum", buildnum.ToString(),"APP");
            //PlayerSettings.Android.bundleVersionCode = buildnum;

            ////////////////渠道... >>>> 1.包内的 
            //string channel = info_buildparam["channel"].AsString;
            //_versionIni.Set("channel", channel,"APP");

            ////////////////GIT 提交编号... >>>> 1.包内的 
            //string gitnum = info_buildparam["gitnum"].AsString;
            //_versionIni.Set("gitnum", gitnum,"APP");

            try
            {
                ActionForApplyShellBuildParam?.Invoke(info_version);
            }
            catch (Exception ex)
            {
                Debug.Log($"[JenkinsBuilder.ActionForApplyShellBuildParam]:Error:{ex.Message}");
            }



        }




        [MenuItem("MIYA/Build/BuildALL")]
        public static void BuildALL()
        {

            BuildReport report;
#if UNITY_ANDROID
            RealBuild_Android();
#elif UNITY_IOS
            RealBuild_IOS();
#elif UNITY_WEBGL
            report = RealBuild_WebGL();
#endif

            if (report != null)
            {
                Report(report);
            }

            //打开输出目录
            Application.OpenURL($"{PATH_OUTPUT}");
        }


        static void Report(BuildReport report)
        {
            if (report == null) return;

            // 记录 步骤日志.
            try
            {
                string lines = "-------------------steps-----------------";
                foreach (var step in report.steps)
                {
                    lines += $"\n\n----------STEP[{step.name}] time={step.duration}\n";
                    foreach (var msg in step.messages)
                    {
                        lines += $"[{msg.type}]\t{msg.content}\n";
                    }
                }
                var _logFile = File.Create(Path.Combine(PATH_OUTPUT , "_report.steps.log"));
                _logFile.Write(System.Text.Encoding.UTF8.GetBytes(lines));
                _logFile.Flush(); _logFile.Close();
            }
            catch (Exception ex)
            {

            }


            // 记录 构建文件日志.
            try
            {
                string _lines = "-------------------files-----------------\n";
                int n = 0;
                ulong _sizeall = 0;
                foreach (var f in report.files)
                {
                    _sizeall += f.size;
                    _lines += $"{++n}\t{f.size / 1024}\t{f.path} \n";
                }
                _lines = $"----文件总计:{n} \t {_sizeall * 1.0f / 1024 / 1024}MB \n" + _lines;

                var _logFile = File.Create(Path.Combine(PATH_OUTPUT, "_report.files.log"));
                _logFile.Write(System.Text.Encoding.UTF8.GetBytes(_lines));
                _logFile.Flush(); _logFile.Close();
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
            }
        }
        static Action<NLIni> ActionForApplyShellBuildParam;
        public static void WAITApplyShellBuildPara(Action<NLIni> on)
        {
            ActionForApplyShellBuildParam = on;
        }







    }
}
